package handler

import (
	"strconv"
	"time"

	"github.com/gin-gonic/gin"

	"hrms-api/model"
)

// CreateRecruitment 创建招聘职位
func CreateRecruitment(c *gin.Context) {
	var recruitment model.Recruitment
	if err := c.ShouldBindJSON(&recruitment); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	// 设置发布人ID
	recruitment.Publisher = c.GetUint("user_id")

	if err := model.DB.Create(&recruitment).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, recruitment)
}

// UpdateRecruitment 更新招聘职位信息
func UpdateRecruitment(c *gin.Context) {
	id := c.Param("id")
	var recruitment model.Recruitment

	if err := model.DB.First(&recruitment, id).Error; err != nil {
		NotFound(c, "Recruitment not found")
		return
	}

	if err := c.ShouldBindJSON(&recruitment); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	if err := model.DB.Save(&recruitment).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, recruitment)
}

// GetRecruitment 获取招聘职位详情
func GetRecruitment(c *gin.Context) {
	id := c.Param("id")
	var recruitment model.Recruitment

	if err := model.DB.Preload("User").First(&recruitment, id).Error; err != nil {
		NotFound(c, "Recruitment not found")
		return
	}

	Success(c, recruitment)
}

// ListRecruitments 获取招聘职位列表
func ListRecruitments(c *gin.Context) {
	var recruitments []model.Recruitment
	query := model.DB.Model(&model.Recruitment{}).Preload("User")

	// 支持按状态筛选
	if status := c.Query("status"); status != "" {
		query = query.Where("status = ?", status)
	}

	// 支持按部门筛选
	if department := c.Query("department"); department != "" {
		query = query.Where("department = ?", department)
	}

	// 支持按时间范围筛选
	if startDate := c.Query("start_date"); startDate != "" {
		query = query.Where("start_date >= ?", startDate)
	}
	if endDate := c.Query("end_date"); endDate != "" {
		query = query.Where("end_date <= ?", endDate)
	}

	if err := query.Find(&recruitments).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, recruitments)
}

// DeleteRecruitment 删除招聘职位
func DeleteRecruitment(c *gin.Context) {
	id := c.Param("id")
	var recruitment model.Recruitment

	if err := model.DB.First(&recruitment, id).Error; err != nil {
		NotFound(c, "Recruitment not found")
		return
	}

	if err := model.DB.Delete(&recruitment).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, nil)
}

// UpdateRecruitmentStatus 更新招聘职位状态
func UpdateRecruitmentStatus(c *gin.Context) {
	id := c.Param("id")
	var recruitment model.Recruitment

	if err := model.DB.First(&recruitment, id).Error; err != nil {
		NotFound(c, "Recruitment not found")
		return
	}

	type StatusUpdate struct {
		Status int `json:"status" binding:"required"`
	}

	var update StatusUpdate
	if err := c.ShouldBindJSON(&update); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	// 更新状态
	recruitment.Status = update.Status
	if update.Status == 3 { // 如果状态为已结束，设置结束日期
		recruitment.EndDate = time.Now()
	}

	if err := model.DB.Save(&recruitment).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, recruitment)
}

// ApplyRecruitment 投递简历
func ApplyRecruitment(c *gin.Context) {
	// 获取当前用户ID（候选人）
	userID, exists := c.Get("user_id")
	if !exists {
		Unauthorized(c, "用户未认证")
		return
	}

	// 解析请求参数
	type ApplyRequest struct {
		PositionID uint   `json:"position_id" binding:"required"`
		ResumeURL  string `json:"resume_url" binding:"required"`
	}

	var req ApplyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, err.Error())
		return
	}

	// 检查职位是否存在
	var position model.Position
	if err := model.DB.First(&position, req.PositionID).Error; err != nil {
		NotFound(c, "职位不存在")
		return
	}

	// 检查用户信息是否存在
	var user model.User
	if err := model.DB.First(&user, userID).Error; err != nil {
		NotFound(c, "用户信息不存在")
		return
	}

	// 获取候选人信息
	var candidate model.Candidate
	result := model.DB.Where("user_id = ?", userID).First(&candidate)

	if result.Error != nil {
		// 如果用户第一次应聘，创建候选人记录
		candidate = model.Candidate{
			UserID: userID.(uint),
			Name:   user.Username, // 临时使用用户名作为应聘者姓名，用户可以在个人资料中修改
			Status: 0,             // 0-待审核
		}
		if err := model.DB.Create(&candidate).Error; err != nil {
			InternalServerError(c, "创建候选人记录失败")
			return
		}
	}

	// 创建应聘记录
	application := model.Candidate{
		UserID:     userID.(uint),
		Name:       candidate.Name,
		PositionID: req.PositionID,
		ResumeURL:  req.ResumeURL,
		Status:     0, // 0-待审核
		ApplyDate:  time.Now(),
	}

	if err := model.DB.Create(&application).Error; err != nil {
		InternalServerError(c, "投递简历失败")
		return
	}

	Success(c, gin.H{
		"apply_id": application.ID,
		"message":  "投递成功",
	})
}

// ListCandidates 获取应聘者列表
func ListCandidates(c *gin.Context) {
	// 检查权限（只有HR和管理员可以查看应聘者列表）
	userRole, exists := c.Get("role")
	if !exists || (userRole != "hr" && userRole != "admin") {
		Forbidden(c, "需要HR或管理员权限")
		return
	}

	// 分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	keyword := c.Query("keyword")
	positionID := c.Query("position_id")
	status := c.Query("status")

	// 构建查询
	query := model.DB.Model(&model.Candidate{})

	// 关键词搜索
	if keyword != "" {
		query = query.Where("name LIKE ?", "%"+keyword+"%")
	}

	// 职位筛选
	if positionID != "" && positionID != "0" {
		query = query.Where("position_id = ?", positionID)
	}

	// 状态筛选
	if status != "" && status != "0" {
		query = query.Where("status = ?", status)
	}

	// 统计总数
	var total int64
	query.Count(&total)

	// 查询分页数据
	var candidates []model.Candidate
	query = query.Preload("Position").Offset((page - 1) * pageSize).Limit(pageSize).Order("id DESC")
	if err := query.Find(&candidates).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	// 格式化响应数据
	var result []map[string]interface{}
	for _, candidate := range candidates {
		var positionName string
		if candidate.Position.ID > 0 {
			positionName = candidate.Position.Name
		} else {
			positionName = "未知"
		}

		result = append(result, map[string]interface{}{
			"id":         candidate.ID,
			"name":       candidate.Name,
			"position":   positionName,
			"education":  candidate.Education,
			"school":     candidate.GraduationSchool,
			"apply_date": candidate.ApplyDate.Format("2006-01-02"),
			"status":     candidate.Status,
		})
	}

	Success(c, gin.H{
		"total": total,
		"list":  result,
		"page":  page,
		"size":  pageSize,
	})
}

// ArrangeInterview 安排面试
func ArrangeInterview(c *gin.Context) {
	// 检查权限（只有HR和管理员可以安排面试）
	userRole, exists := c.Get("role")
	if !exists || (userRole != "hr" && userRole != "admin") {
		Forbidden(c, "需要HR或管理员权限")
		return
	}

	// 解析请求参数
	type InterviewRequest struct {
		CandidateID    uint   `json:"candidate_id" binding:"required"`
		InterviewTime  string `json:"interview_time" binding:"required"`
		Location       string `json:"location" binding:"required"`
		InterviewerIDs []uint `json:"interviewer_ids"`
		Remark         string `json:"remark"`
	}

	var req InterviewRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, err.Error())
		return
	}

	// 检查候选人是否存在
	var candidate model.Candidate
	if err := model.DB.First(&candidate, req.CandidateID).Error; err != nil {
		NotFound(c, "候选人不存在")
		return
	}

	// 解析面试时间
	interviewTime, err := time.Parse("2006-01-02 15:04:05", req.InterviewTime)
	if err != nil {
		BadRequest(c, "面试时间格式不正确，请使用 yyyy-MM-dd HH:mm:ss 格式")
		return
	}

	// 创建面试记录
	interview := model.Interview{
		CandidateID:  candidate.ID,
		PositionID:   candidate.PositionID,
		ScheduleTime: interviewTime,
		Location:     req.Location,
		Type:         1, // 1-初试
		Status:       1, // 1-待面试
		Notes:        req.Remark,
	}

	if err := model.DB.Create(&interview).Error; err != nil {
		InternalServerError(c, "创建面试记录失败")
		return
	}

	// 更新候选人状态为已安排面试
	if err := model.DB.Model(&candidate).Update("status", 2).Error; err != nil {
		InternalServerError(c, "更新候选人状态失败")
		return
	}

	Success(c, gin.H{
		"interview_id": interview.ID,
		"message":      "面试安排成功",
	})
}
